package com.kg.fiber.view;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;

import com.kg.fiber.FiberviewApplication;
import com.kg.fiber.service.NodeBoss;
import com.kg.fiber.service.NodeModal;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.ListSelectionEvent;

public class NodeListPanel extends JPanel {

	/**
	 * 
	 */
	private static final long serialVersionUID = 2492267011345460753L;
	private JButton btnRemove;
	private JList<NodeModal> list;

	/**
	 * Create the panel.
	 */
	public NodeListPanel() {
		setLayout(new BorderLayout(0, 0));
		
		JScrollPane scrollPane = new JScrollPane();
		add(scrollPane, BorderLayout.CENTER);
		
		list = new JList<NodeModal>();
		list.addListSelectionListener(new ListSelectionListener() {
			public void valueChanged(ListSelectionEvent e) {
				NodeModal selected = list.getSelectedValue();
				btnRemove.setEnabled(selected != null);
			}
		});
		list.setCellRenderer(new NodePanel());
		scrollPane.setViewportView(list);
		
		NodePanel nodePanel = new NodePanel();
		nodePanel.setPreferredSize(new Dimension(551, 40));
		scrollPane.setColumnHeaderView(nodePanel);
		
		NodeBoss boss = FiberviewApplication.getSpring().getBean(NodeBoss.class);
		list.setModel(boss.getListModel());
		
		JPanel panel = new JPanel();
		panel.setPreferredSize(new Dimension(10, 40));
		add(panel, BorderLayout.NORTH);
		panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
		
		Component horizontalGlue = Box.createHorizontalGlue();
		panel.add(horizontalGlue);
		
		JButton btnAdd = new JButton("添加节点");
		btnAdd.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				AddNodeDialog dialog = new AddNodeDialog();
				dialog.start(NodeListPanel.this);
			}
		});
		btnAdd.setFont(new Font("微软雅黑", Font.PLAIN, 18));
		panel.add(btnAdd);
		
		Component horizontalStrut = Box.createHorizontalStrut(8);
		panel.add(horizontalStrut);
		
		btnRemove = new JButton("删除节点");
		btnRemove.setEnabled(false);
		btnRemove.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				NodeModal selected = list.getSelectedValue();
				if(selected != null) {
					NodeBoss boss = FiberviewApplication.getSpring().getBean(NodeBoss.class);
					boss.deleteNode(selected.getNode().getHost());
					btnRemove.setEnabled(false);
				}
			}
		});
		btnRemove.setFont(new Font("微软雅黑", Font.PLAIN, 18));
		panel.add(btnRemove);
		
		Component horizontalStrut_1 = Box.createHorizontalStrut(8);
		panel.add(horizontalStrut_1);

	}

}
